<?php
declare(strict_types=1);

namespace App\Job;

use App\Log\Log;
use Hyperf\AsyncQueue\Job;
use Hyperf\Utils\ApplicationContext;
use Hyperf\WebSocketServer\Sender;

class PushGlobalNotificationJob extends Job
{
    public $params;

    public function __construct($params)
    {
        $this->params = $params;
    }

    public function handle()
    {
        $redis = ApplicationContext::getContainer()->get(\Redis::class);
        $keys = $redis->keys('Remit_WebSocketGlobalController_fd_with_user_id*');

        foreach ($keys as $key) {
            $fd = $redis->get($key);
            // 存在 fd, 发送通知
            if ($fd) {
                try {
                    ApplicationContext::getContainer()->get(Sender::class)->push((int)$fd, json_encode([
                        'type' => $this->params['type'],
                        'body' => $this->params
                    ]));
                } catch (\Exception $e) {
                    Log::error('PushGlobalNotificationJob:   ' . $e->getMessage());
                }
            }
        }
    }
}
